/*
 * Copyright 2014-2020  the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.upb.webserver.security;

import com.upb.webserver.account.AccountService;
import com.upb.webserver.common.enums.PlatformEnum;
import com.upb.webserver.common.enums.TokenTypeEnum;
import com.upb.webserver.common.pojo.account.AccountCommon;
import com.upb.webserver.common.pojo.base.BaseResponse;
import com.upb.webserver.common.returncode.ConstantCode;
import com.upb.webserver.common.tools.JsonUtils;
import com.upb.webserver.dao.entity.TbCompany;
import com.upb.webserver.dao.entity.TbCompanyDeveloper;
import com.upb.webserver.dao.mapper.TbCompanyDeveloperMapper;
import com.upb.webserver.dao.mapper.TbCompanyMapper;
import com.upb.webserver.dao.mapper.TbTokenMapper;
import com.upb.webserver.token.TokenService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Log4j2
@Component("loginSuccessHandler")
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private AccountService accountService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private TbTokenMapper tbTokenMapper;
    @Autowired
    private TbCompanyDeveloperMapper tbCompanyDeveloperMapper;
    @Autowired
    private TbCompanyMapper companyMapper;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication)
            throws IOException, ServletException {
        log.debug("login success");

        String accountJsonBase64 = authentication.getName();

        //delete old token and save new
        tbTokenMapper.deleteByValue(accountJsonBase64);
        String token = tokenService.createToken(accountJsonBase64, TokenTypeEnum.USER.getId());

        // response account info
        AccountCommon account = accountService.getAccountCommon(accountJsonBase64);
        Map<String, Object> rsp = new ConcurrentHashMap<>();
        rsp.put("roleName", account.getRoleName());
        rsp.put("account", account.getAccount());
        rsp.put("accountStatus", account.getStatus());

        if (PlatformEnum.DEVELOPER.getId() == account.getPlatform()) {
            TbCompanyDeveloper tbCompanyDeveloper = tbCompanyDeveloperMapper.selectByDeveloper(account.getId());
            TbCompany tbCompany = companyMapper.selectByPrimaryKey(tbCompanyDeveloper.getCompanyId());
            rsp.put("companyId", tbCompanyDeveloper.getCompanyId());
            rsp.put("companyName", tbCompany.getCompanyName());
        }

        rsp.put("token", token);


        BaseResponse baseResponse = new BaseResponse(ConstantCode.SUCCESS);
        baseResponse.setData(rsp);

        String backStr = JsonUtils.objToString(baseResponse);
        log.info("success exec method [onAuthenticationSuccess]. backStr:{}", backStr);

        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(backStr);
    }
}
